package lg.minecraft.plugin.pokedex.item.builder;

import com.cobblemon.mod.common.pokemon.Species;
import lg.minecraft.plugin.cobblemoncore.util.BukkitNmsConverter;
import lg.minecraft.plugin.library.common.PlaceholderReplacer;
import lg.minecraft.plugin.library.item.ItemProperties;
import lg.minecraft.plugin.library.item.builder.AbstractItemBuilder;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author langle__
 * @version 1.0
 */
public class PokemonRewardItemBuilder extends AbstractItemBuilder {

    private final ItemProperties qualifiedProperties;
    private final ItemProperties claimedProperties;

    public PokemonRewardItemBuilder(ItemProperties qualifiedProperties, ItemProperties claimedProperties) {
        super(qualifiedProperties);
        this.qualifiedProperties = qualifiedProperties;
        this.claimedProperties = claimedProperties;
    }

    @Override
    protected ItemStack build(Map<String, String> map, Object... objects) {
        Species species = (Species) objects[0];
        boolean receive = (boolean) objects[1];
        //noinspection unchecked
        List<String> rewardLoreList = (List<String>) objects[2];
        ItemProperties selected = receive ? claimedProperties : qualifiedProperties;
        ItemStack stack = BukkitNmsConverter.getPokemonItem(species);
        ItemMeta meta = stack.getItemMeta();
        if (meta != null) {
            meta.setDisplayName(PlaceholderReplacer.replaceInString(selected.getName(), map));
            List<String> loreList = new ArrayList<>();
            for (String lore : selected.getLore()) {
                if (lore.equalsIgnoreCase("{reward}")) {
                    loreList.addAll(PlaceholderReplacer.replaceInList(rewardLoreList, map));
                    continue;
                }
                loreList.add(PlaceholderReplacer.replaceInString(lore, map));
            }
            meta.setLore(loreList);
            selected.getEnchantments().forEach((enchantedEntry) -> meta.addEnchant(enchantedEntry.getEnchantment(), enchantedEntry.getLevel(), true));
            selected.getItemFlags().forEach(meta::addItemFlags);
            stack.setItemMeta(meta);
        }

        return stack;
    }

    public ItemStack build(Species species, Map<String, String> map, boolean receive, List<String> lore) {
        return build(map, species, receive, lore);
    }

}
